<?php
namespace Mob \ Model;

use Think \ Model;
use Think \ Hook;
/**请求模型
 * Class InfoModel
 */

require_once ('./Application/Mob/Common/function.php');
class WxCommonModel  {

    protected $appid;
    protected $secrect;
    public $accessToken;

    function  __construct()
    {
        $this->appid = C('Wx_AppID');
        $this->secrect = C('Wx_AppSecret');
        $this->accessToken = $this->getToken();

    }

    /**
     * 发送post请求
     * @param string $url
     * @param string $param
     * @return bool|mixed
     */
    public  function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch); //运行curl
        curl_close($ch);
        return $data;
    }


    /**
     * 发送get请求
     * @param string $url
     * @return bool|mixed
     */
    function request_get($url = '')
    {
        if (empty($url)) {
            return false;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    /**
     * @param $appid
     * @param $appsecret
     * @return mixed
     * 获取token
     */
    public  function getToken()
    {

        if (cache_get('Wx_AccessToken')) {
            $access_token = cache_get('Wx_AccessToken');
        } else {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->secrect;

            $token = $this->request_get($url);

            $token = json_decode(stripslashes($token));
            $arr = json_decode(json_encode($token), true);
            $access_token = $arr['access_token'];

           if($access_token)
           {
            cache_set('Wx_AccessToken',$access_token);
           }else
           {
           return null;
           }

        }

        return $access_token;
    }





    /**
     * 获取微信授权链接
     *
     * @param string $redirect_uri 跳转地址
     * @param mixed $state 参数
     */
    public function get_authorize_url($redirect_uri = '', $state = '')
    {
        $redirect_uri = urlencode($redirect_uri);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state={$state}#wechat_redirect";
    }

    /**
     * 获取授权token
     *
     * @param string $code 通过get_authorize_url获取到的code
     */
    public function get_access_token($app_id = '', $app_secret = '', $code = '')
    {
        $token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->app_secret}&code={$code}&grant_type=authorization_code";
        $token_data = $this->http($token_url);

        if($token_data[0] == 200)
        {
            return json_decode($token_data[1], TRUE);
        }

        return FALSE;
    }

    /**
     * 获取授权后的微信用户信息
     *
     * @param string $access_token
     * @param string $open_id
     */
    public function get_user_info($access_token = '', $open_id = '')
    {
        if($access_token && $open_id)
        {
         //   $info_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$open_id}&lang=zh_CN";
          $info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$open_id}&lang=zh_CN";
            $info_data = $this->http($info_url);

            if($info_data[0] == 200)
            {
                return json_decode($info_data[1], TRUE);
            }
        }

        return FALSE;
    }

    public function http($url, $method, $postfields = null, $headers = array(), $debug = false)
    {
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ci, CURLOPT_TIMEOUT, 30);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);

        switch ($method) {
            case 'POST':
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
                    $this->postdata = $postfields;
                }
                break;
        }
        curl_setopt($ci, CURLOPT_URL, $url);
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);

        $response = curl_exec($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);

        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);

            echo '=====info=====' . "\r\n";
            print_r(curl_getinfo($ci));

            echo '=====$response=====' . "\r\n";
            print_r($response);
        }
        curl_close($ci);
        return array($http_code, $response);
    }
   public function http_get($get_token_url)
   {
   $ch = curl_init();
   curl_setopt($ch,CURLOPT_URL,$get_token_url);
   curl_setopt($ch,CURLOPT_HEADER,0);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
   curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
   $res = curl_exec($ch);
   curl_close($ch);
   return $json_obj = json_decode($res,true);

   }

   public function get_AuthorizeUrl($redirect_uri,$scope='snsapi_userinfo',$state='')
   {

   	if(empty($state))
   	{
   	$state = getSerialno();
   	}
   	return $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->appid.'&redirect_uri='.urlencode($redirect_uri).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';

   }
   public function get_TokenUrl($code)
   {

   return $url ='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appid.'&secret='.$this->secrect.'&code='.$code.'&grant_type=authorization_code';

   }
   public function get_Token($code)
   {
   $url = $this->get_TokenUrl($code);
   return $res = $this->http_get($url);

   }
   public function get_UserInfoUrl($openid,$access_token)
   {
   return    $info_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";

   }
   public function get_UserInfo($openid,$access_token)
   {
   $url = $this->get_UserInfoUrl($openid,$access_token);
   $res = $this->http_get($url);
   return $res;
   }
   //获取access_token
   public function get_accessToken()
   {
    return 	$this->accessToken;
   }
   //获取调用jsapi的URL
   private function get_JsApiTicketUrl($access_token)
   {
  // return  $info_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$this->accessToken."&amp;type=jsapi";
  return  $info_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$this->accessToken."&type=jsapi";

   }
   public function get_JsApiTicket()
   {
   	$jsapi_ticket = cache_get('Wx_jsapi_ticket');
   	if($jsapi_ticket)
   	{
   	return $jsapi_ticket;
   	}else
   	{
   	$jsapiUrl = $this->get_JsApiTicketUrl();  //获取jsapi地址的url
    $jsapi_res = $this->http_get($jsapiUrl); //取返回结果
    if($jsapi_res['errcode']==0)//判断jsapi接口是否返回成功
    {
    $jsapi_ticket = $jsapi_res['ticket'];
     cache_set('Wx_jsapi_ticket',$jsapi_ticket); //更新缓存
     return $jsapi_ticket;
    }

   	}

    }
    // 生成随机字符串
    public function createNonceStr($length = 16)
    {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i< $length; $i++) {
    $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
    }
    //拼装签名
    public function get_js_sdk($url){

    $protocol = (!empty($_SERVER[HTTPS]) &&$_SERVER[HTTPS] !== off || $_SERVER[SERVER_PORT] == 443) ? "https://" : "http://";
    $url=empty($url)?$url = $protocol.$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI]:$url;
    $argu = array();
    $argu[appId] = $this->appid;
    $argu[url] = $url;
    $argu[nonceStr] = $this->createNonceStr();
    $argu[timestamp] = time();
    $argu[jsapi_ticket] = $this->get_JsApiTicket();
    $string = "jsapi_ticket=".$argu[jsapi_ticket]."&noncestr=".$argu[nonceStr]."&timestamp=".$argu[timestamp]."&url=".$argu[url];
    $argu[signature] = sha1(trim($string));
    return $argu;
    }


}